const express = require('express');
// const db = require('../db');
const {mongoFind, mongoInsert} = require('../db.js')
const md5 = require('md5')
const router = express.Router();



router.get('/', function(req, res, next) {
    res.redirect('./product')
});

router.get('/login', function(req, res, next) {
    res.render('login', { msg: null });
});

router.post('/login', function(req, res, next) {
    var userData = { username: req.body.username, password: md5(req.body.password) }
    mongoFind('user', userData, function(doc) {
        var user = doc[0]
        if (user) {
            if (req.body.remember) {
                req.sessionOptions.maxAge = 24 * 60 * 60 * 1000
            }
            req.session.uid = user['_id'];
            req.app.locals.user = user
            console.log('login----')
            res.redirect('/')
        }
        res.render('login', { msg: "用户名或者密码错误！" })
    })
});

router.get('/loginout', function(req, res, next) {
    req.session = null
    req.app.locals.user = null
    res.redirect('/login')
})

router.get('/db', function(req, res, next) {
    
    mongoFind('user', {}, function(doc) {
        res.json(doc)
    })
})

router.get('/json', function(req, res, next) {
    res.json({
        name: 'zhangsan',
        age: 20
    })
})


module.exports = router;